package com.lesserpand.springcloudalibabaprovider.utils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;

/**
 * @author bailuo
 * @version 2.0
 * @Description TODO
 * @Date Created in 2018/12/10 17:08
 */
public class HttpUtils {


    static HostnameVerifier hv = (urlHostName, session) -> true;

    public static String connectingAddress(String remoteInetAddr) {
        boolean flag = false;
        //取出地址前5位
        String tempUrl = remoteInetAddr.substring(0, 5);
        //判断传过来的地址中是否有http
        if (tempUrl.contains("http")) {
            //判断服务器是否是https协议
            if (tempUrl.equals("https")) {
                try {
                    //当协议是https时
                    trustAllHttpsCertificates();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //当协议是https时
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
            }
            flag = isConnServerByHttp(remoteInetAddr);
        } else {//传过来的是IP地址
            flag = isReachable(remoteInetAddr);
        }
        if (flag) {
            return "正常";
        } else {
            return "异常";
        }
    }

    /**
     *   * 传入需要连接的IP，返回是否连接成功
     *      *
     *      * @param remoteInetAddr
     *      * @return
     *     
     */

    public static boolean isReachable(String remoteInetAddr) {
        // IP地址是否可达，相当于Ping命令
        boolean reachable = false;
        try {
            InetAddress address = InetAddress.getByName(remoteInetAddr);
            reachable = address.isReachable(1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reachable;
    }

    /**
     * 服务器是否开启
     */
    public static boolean isConnServerByHttp(String serverUrl) {
        boolean connFlag = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL(serverUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            // 如果连接成功则设置为true
            if (conn.getResponseCode() == 200) {
                connFlag = true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }
        return connFlag;
    }

    /*以下是Https适用*/
    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements TrustManager, X509TrustManager {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }
    /*以上是Https适用*/

}
